package com.foolishbird.sdk.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;


import com.foolishbird.sdk.system.DeviceInfo;
import com.tencent.mm.opensdk.modelbiz.JumpToBizProfile;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.io.File;
import java.util.List;



public final class ToolsUtils {

    private static final String TAG = ToolsUtils.class.getSimpleName();

    private ToolsUtils() {
    }

    /**
     * 验证手机号码
     * <p>
     * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147
     * 联通号码段:130、131、132、136、185、186、145
     * 电信号码段:133、153、180、189
     *
     * @param cellphone
     * @return
     */
    public static boolean checkCellphone(String cellphone) {
        if (TextUtils.isEmpty(cellphone)) {
            return false;
        }
        return cellphone.matches("^1[2|3|4|5|6|7|8|9][0-9]{9}$");
    }

    public static boolean checkNumber(String number) {
        if (TextUtils.isEmpty(number)) {
            return false;
        }
        return number.matches("^[0-9]*$");
    }

    public static boolean checkIdentityCardNumber(String number) {
        if (TextUtils.isEmpty(number)) {
            return false;
        }
        return number.matches("^[1-9][0-9]{16}[0-9Xx]$");
    }

    /**
     * 检查微信是否存在
     *
     * @param context
     * @return
     */
    public static boolean isInstallWeixin(Context context) {
        if (context != null) {
            IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, null);
            if (iwxapi.isWXAppInstalled()) {
                return true;
            } else {
                return DeviceInfo.isInstalledWeChat(context);
            }
        }
        return false;
    }

    /**
     * 检查云闪付是否安装
     *
     * @param context
     * @return
     */
    public static boolean isInstallUnionPay(Context context) {
        if (context != null) {
            if (UPPayAssistEx.checkWalletInstalled(context.getApplicationContext())) {
                return true;
            } else {
                return DeviceInfo.isInstalledUnionPay(context.getApplicationContext());
            }
        }
        return false;
    }

    public static void startWeChatPublicNumber(Context context, String appId, String originalAppId) {
        IWXAPI api = WXAPIFactory.createWXAPI(context, appId);
        if (api.isWXAppInstalled()) {
            api.registerApp(appId);

            JumpToBizProfile.Req req = new JumpToBizProfile.Req();
            req.toUserName = originalAppId;
            req.extMsg = "start wechat public number";
            req.profileType = JumpToBizProfile.JUMP_TO_NORMAL_BIZ_PROFILE;

            api.sendReq(req);
        }
    }

    public static boolean isActivityForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;
    }

    public static boolean checkAppSelfPermission(Context context, String permission) {
        if (context != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                int result = ActivityCompat.checkSelfPermission(context.getApplicationContext(), permission);
                return PackageManager.PERMISSION_GRANTED == result;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    public final static boolean isNumberType(String number) {
        try {
            Long.valueOf(number);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public final static File getExternalStorageDirectory() {
        return new File(Environment.getExternalStorageDirectory(), "hunan669");
    }

    public final static boolean checkAndMakeStorageDirectory(File directory) {
        if (directory != null) {
            if (directory.isDirectory()) {
                if (!directory.exists()) {
                    return directory.mkdirs();
                }
            } else {
                File parent = directory.getParentFile();
                if (!parent.exists()) {
                    return parent.mkdirs();
                }
            }
            return true;
        }
        return false;
    }

    public final static <T> T createInstance(String className) {
        WL.d(TAG, "createInstance  -----> className: " + className);
        T instance = null;
        try {
            Class<?> clazz = Class.forName(className);
            Object object = clazz.getDeclaredConstructor().newInstance();
            try {
                instance = (T) object;
            } catch (ClassCastException e) {
                e.printStackTrace();
                WL.e(TAG, "createInstance  -----> ClassCastException. className: " + className);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            WL.e(TAG, "createInstance  -----> ClassNotFoundException. className: " + className);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            WL.e(TAG, "createInstance  -----> NoSuchMethodException. className: " + className);
        } catch (InstantiationException e) {
            e.printStackTrace();
            WL.e(TAG, "createInstance  -----> InstantiationException. className: " + className);
        } catch (Exception e) {
            e.printStackTrace();
            WL.e(TAG, "createInstance  -----> Exception. " + e.getLocalizedMessage());
        }
        return instance;
    }

    /**
     * 获取应用程序名称
     */
    public static final String getAppName(Context context) {
        if (context == null) {
            return "";
        }

        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.applicationInfo.loadLabel(pm).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

}
